const { Service } = require('ee-core');
const { execSync } = require('child_process');
const os = require('os');
const settings = require('electron-settings');
const Services = require("ee-core/services");
const {info} = require("ee-core/log");
const sudo = require('sudo-prompt');
const options = {
    name: 'network',
};
class NetworkService extends Service {
    constructor(ctx) {
        super(ctx);
    }

    async getNetworkInterfaces() {
        return os.networkInterfaces();
    }

    async getAllNetworkInterfaces() {
        const networkInterfaces = os.networkInterfaces();
        const interfaces = [];
        for (const [interfaceName, interfaceDetails] of Object.entries(networkInterfaces)) {
            const ipv4Interfaces = interfaceDetails.filter((iface) => iface.family === 'IPv4');
            const ipAddress = ipv4Interfaces.length > 0 ? ipv4Interfaces[0].address : null;
            interfaces.push({ interfaceName, ipAddress });
        }
        return interfaces;
    }

    async getIPAddress(interfaceName) {
        const networkInterfaces = os.networkInterfaces();
        const interfaces = networkInterfaces[interfaceName];
        if (interfaces && interfaces.length > 0) {
            return interfaces[0].address;
        }
        return 0;
    }

    async getIPv4Address(interfaceName) {
        const networkInterfaces = os.networkInterfaces();
        const interfaces = networkInterfaces[interfaceName];
        if (interfaces && interfaces.length > 0) {
            const ipv4Interfaces = interfaces.filter((iface) => iface.family === 'IPv4');
            if (ipv4Interfaces.length > 0) {
                return ipv4Interfaces[0].address;
            }
        }
        return null;
    }

    /**
     * 网卡切换到自动
     * @param interfaceName
     * @param classRoom
     * @returns {Promise<boolean>}
     */
    async setIPDhcp(interfaceName) {
        try {
            // 构建设置 IP 地址的命令
            const setIpCommand = `netsh interface ipv4 set address name="${interfaceName}" dhcp`;
            // 构建设置 DNS 的命令
            const setDnsCommand1 = `netsh interface ipv4 set dns name="${interfaceName}" source=dhcp`;

            // 一次性执行所有命令
            await new Promise((resolve, reject) => {
                sudo.exec(`${setIpCommand} && ${setDnsCommand1}`, options, (error, stdout, stderr) => {
                    if (error) {
                        // console.error('Failed to set IP address:', error);
                        reject(error);
                        return false;
                    } else {
                        resolve();
                        return true;
                    }
                });
            });
            // 更新设置成功后的配置信息
            // await settings.set(`networkInterfaces.${interfaceName}.ipAddress`, result.ipAddress);
            return true;
        } catch (error) {
            console.error('Failed to set IP address:', error);
            return false;
        }
    }

    /**
     * 切换网卡IP
     * @param interfaceName
     * @param classRoom
     * @returns {Promise<boolean>}
     */
    async setIPAddress(interfaceName, classRoom) {
        try {
            // 读取数据库中该教室数据
            const result = await Services.get('jsondb').getTestData({classRoom: classRoom});
            info('service result:', result);
            if (Array.isArray(result) && result.length === 0) {
                return false;
            }
            // 构建设置 IP 地址的命令
            const setIpCommand = `netsh interface ipv4 set address name="${interfaceName}" source=static address=${result.ipAddress} mask=255.255.255.0 gateway=${result.gateway}`;

            // 构建设置 DNS 的命令
            const setDnsCommand1 = `netsh interface ipv4 set dns name="${interfaceName}" source=static addr=${result.DNSA} register=PRIMARY`;
            const setDnsCommand2 = `netsh interface ipv4 add dns name="${interfaceName}" addr=${result.DNSB} index=2`;

            // 一次性执行所有命令
            //execSync(`${setIpCommand} && ${setDnsCommand1} && ${setDnsCommand2}`);
            // 一次性执行所有命令
            await new Promise((resolve, reject) => {
                sudo.exec(`${setIpCommand} && ${setDnsCommand1} && ${setDnsCommand2}`, options, (error, stdout, stderr) => {
                    if (error) {
                       // console.error('Failed to set IP address:', error);
                        reject(error);
                        return false;
                    } else {
                        resolve();
                        return true;
                    }
                });
            });
            // 更新设置成功后的配置信息
           // await settings.set(`networkInterfaces.${interfaceName}.ipAddress`, result.ipAddress);
            return true;
        } catch (error) {
            console.error('Failed to set IP address:', error);
            return false;
        }
    }
}

NetworkService.toString = () => '[class NetworkService]';
module.exports = NetworkService;